<template>
    <cardComponent id="insBillAppli-contnair" v-loading="isLoading" pageTitle="账单分期申请">
        <template slot="cardBody">
            <el-form ref="dailyFormRef" :model="dailyForm" label-width="120px" size="small">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="账户类别:" class="text_fl">
                            <el-select
                                v-model="dailyForm.accttype"
                                placeholder="请选择账户类别"
                                disabled
                                @change="changeCardList"
                            >
                                <el-option
                                    v-for="item in AccountionTYPE_INFO"
                                    :label="item.label"
                                    :value="item.code"
                                    :key="item.label"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="卡号:" class="text_fl">
                            <el-select v-model="dailyForm.cardno" placeholder="请选择卡号" disabled>
                                <el-option
                                    v-for="item in cardList"
                                    :label="item.CARDNBR"
                                    :value="item.CARDNBR"
                                    :key="item.CARDNBR"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="分期计划编号:">
                            <el-select
                                placeholder="请选择分期计划编号"
                                @change="getCREDNOValue"
                                v-model="dailyForm.CREDNO"
                            >
                                <el-option
                                    v-for="(item, index) in stmtplanList"
                                    :key="index"
                                    :label="item.code + ' -- ' + item.label"
                                    :value="item.code"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <div class="footer">
                    <el-button type="primary" size="small" @click="searchData">查 询</el-button>
                </div>-->
            </el-form>
            <div v-if="showTrial">
                <el-divider content-position="center"></el-divider>
                <!-- <el-card shadow="never" style="margin-top:16px;">
                    <el-row>
                        <el-col :span="4">信用计划编号:</el-col>
                        <el-col :span="7">{{CREDNO}}</el-col>
                        <el-col :span="5">截止昨日未还消费余额:</el-col>
                        <el-col :span="8">{{UNBALFRE}}</el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4">参考申请金额:</el-col>
                        <el-col :span="7">{{refamt}}</el-col>
                        <el-col :span="5">分期金额:</el-col>
                        <el-col :span="8">
                            <el-input
                                class="payAcount"
                                type="number"
                                v-model="payAcount"
                                @blur="handleBlur"
                            ></el-input>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="4">本期账单金额:</el-col>
                        <el-col :span="7">{{openamt}}</el-col>
                        <el-col :span="5">差额:</el-col>
                        <el-col :span="8">{{difference}}</el-col>
                    </el-row>
                </el-card>-->
                <el-table
                    :data="stmtData"
                    border
                    class="heard-bg business_table"
                    style="width: 100%;"
                    size="small"
                >
                    <el-table-column prop="CREDNO" label="分期计划编号"></el-table-column>
                    <el-table-column prop="OPENAMT" label="本期账单金额"></el-table-column>
                    <el-table-column prop="UNBALFRE" label="本期账单未还金额"></el-table-column>
                    <el-table-column prop="REFAMT" label="参考申请金额"></el-table-column>

                    <!-- <el-table-column prop="REMSTMAMT" label="账单可分期账单金额"></el-table-column> -->
                    <el-table-column prop="payAcount_val" label="分期金额">
                        <template slot-scope="scope">
                            <el-input
                                class="payAcount"
                                v-model="scope.row.payAcount_val"
                                @blur="handleBlur"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="BALANCEMAMT" label="差额"></el-table-column>
                </el-table>

                <el-divider content-position="center">费用试算表</el-divider>
                <el-table
                    :data="tryData"
                    border
                    class="heard-bg business_table"
                    style="width: 100%;"
                    size="small"
                >
                    <el-table-column prop="OUTFLAG" label="选择分期期数">
                        <template slot-scope="scope">
                            <el-select
                                v-model="scope.row.OUTFLAG"
                                style="width: 100%;"
                                placeholder="选择分期期数"
                                @change="toCount11"
                            >
                                <el-option
                                    v-for="(item, index) in setMonthRate"
                                    :key="index"
                                    :label="item.label"
                                    :value="item.MPMONTH"
                                ></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="CORPUS" label="首期还款额"></el-table-column>

                    <el-table-column prop="REMONTHFEE" label="每期还款额"></el-table-column>

                    <el-table-column prop="ALLMONTHSFEE" label="分期总手续费"></el-table-column>

                    <el-table-column prop="ALLCOUNTFEE" label="总还款额"></el-table-column>
                </el-table>
                <el-divider v-if="flag" content-position="center">已申请账单分期信息</el-divider>
                <el-table
                    v-if="flag"
                    :data="haveAppData"
                    border
                    class="heard-bg business_table"
                    style="width: 100%;"
                    size="small"
                >
                    <el-table-column prop="CREDNO" label="分期计划编号"></el-table-column>
                    <el-table-column prop="NBRMTHS" label="分期期数"></el-table-column>
                    <!-- 一次 -->
                    <el-table-column prop="AMT" label="分期金额"></el-table-column>
                    <el-table-column prop="INSTALAMT" label="每月还款额"></el-table-column>
                    <el-table-column prop="UNSTM" label="截止昨日未还账单余额"></el-table-column>
                </el-table>
                <!-- 话术 -->
                <div class="hstable_wrap" v-if="speechList.length!=0">
                    <el-table
                        :data="speechList"
                        border
                        stripe
                        header-row-class-name="headerRow"
                        ref="showListTable"
                        class="heard-bg business_table hstable"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                        <el-table-column label="业务话术">
                            <template slot-scope="scope">{{scope.row.content}}</template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="footer">
                    <el-button type="primary" size="small" @click="handleApplication">申 请</el-button>
                    <el-button type="primary" size="small" @click="handleClicksuInfo">多期数试算结果</el-button>
                    <el-button type="primary" size="small" @click="applicationRecords">分期付款申请记录</el-button>
                </div>

                <el-dialog
                    title="多期数试算结果"
                    v-drag
                    :visible.sync="DialogVisible"
                    width="900px"
                    :append-to-body="true"
                    top="20vh"
                    :close-on-click-modal="false"
                    center
                >
                    <trialbalance :TrialDataList="TrialDataList"></trialbalance>

                    <span slot="footer" class="dialog-footer">
                        <el-button type="primary" size="small" @click="DialogVisible = false">关 闭</el-button>
                    </span>
                </el-dialog>
                <el-dialog
                    v-drag
                    :visible.sync="DialogVisible1"
                    width="900px"
                    :append-to-body="true"
                    top="20vh"
                    :close-on-click-modal="false"
                    center
                >
                    <trialbalance1 :TrialDataList="TrialDataList"></trialbalance1>

                    <span slot="footer" class="dialog-footer">
                        <el-button type="primary" size="small" @click="DialogVisible1 = false">关 闭</el-button>
                    </span>
                </el-dialog>

                <!-- 二次确认办理弹窗 -->
                <el-dialog
                    v-drag
                    title="账单分期申请确认"
                    :visible.sync="secConfirmDialogVisible"
                    width="500px"
                    :append-to-body="true"
                    top="30vh"
                    :close-on-click-modal="false"
                    center
                >
                    <p>
                        分期金额:
                        <span>{{this.secondConfirm.totalAmount}}</span>
                    </p>
                    <p>
                        期数:
                        <span>{{this.secondConfirm.months}}</span>
                    </p>
                    <p>
                        手续费分摊方式:
                        <span>{{this.secondConfirm.pmethod}}</span>
                    </p>
                    <p>
                        费率:
                        <span>{{this.secondConfirm.rate}}</span>
                    </p>
                    <p style="text-align:center;padding-left:0px;">
                        <span style="color:#3a8ee6; ">您确认要申请吗？</span>
                    </p>
                    <span slot="footer" class="dialog-footer">
                        <el-button
                            size="small"
                            icon="el-icon-circle-close"
                            @click="secConfirmDialogVisible = false"
                        >取 消</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            @click="handletrans"
                            icon="el-icon-circle-check"
                            v-preventReClick
                        >确定</el-button>
                    </span>
                </el-dialog>
            </div>
            <!-- 申请成功窗口 -->
            <ConfirmWindow
                v-if="showsuccess"
                @isShow="close"
                :dataList="statementsuccess"
                :title="'账单分期申请成功！'"
            />
        </template>
    </cardComponent>
</template>

<script>
import { mapState } from 'vuex';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import ConfirmWindow from '@/components/ConfirmWindow/ConfirmWindow.vue';
import { closePage, getInstalmentList, getAccountTypeName, getDictSelectList, getBusinessMenuId } from '@/utils/Common';
import { setNumber } from '@/utils/Object';
import { get_4xxx, get_3xxx } from '@/apis/getAPIClass';
import { getTokenHsbankNo } from '@/utils/auth';
import Trialbalance from '@/components/TrialBalance/Trialbalance';
import Trialbalance1 from '@/components/TrialBalance/Trialbalance1';
import moment from 'moment';

export default {
    components: {
        cardComponent,
        ConfirmWindow,
        Trialbalance,
        Trialbalance1,
    },
    name: 'InstallmentBillApplication',
    data() {
        return {
            accountType: '',
            dailyForm: {
                CREDNO: '',
                accttype: '',
                cardno: '',
            },
            showsuccess: false,
            statementsuccess: [],
            feetype: '',
            haveAppData: [],//已办理账单分期申请信息
            CREDNO: '',
            UNBALFRE: '',
            CREDNOLIST: [], // 信用计划编号 下拉选择列表
            Form9105: [], // 申请参考金额 下拉选择列表
            Form9064: [], // 最高可转分期金额选项下拉选择列表
            showTrial: false,
            isLoading: false,
            tran4052Form: {},
            tran3053Form: {},
            refamt: 0,
            openamt: 0,
            difference: '',
            payAcount: '',
            setMonthRate: [],
            TrialDataList: [],//费率表数据
            DialogVisible: false,//
            DialogVisible1: false,
            DialogVisibleSuccess: false,//
            tryData: [
                {
                    OUTFLAG: '',
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                },
            ],
            secConfirmDialogVisible: false,
            secondConfirm: { // 二次确认字段
                rate: '',
                totalAmount: '',
                months: '',
                pmethod: '',
            },
            flag: false,
            cardList: [],
            stmtplanList: [],
            stmtData: [],//账单分期信息
            IccMpprm: '',//分期计划数据
            speechList: [],//话术列表
            selectedList: [],
            MenuId: '',
            newCardAccountInfo_3001: '',//3001new-卡账户信息 每次切换账户更换信息
            stmtamt: '',
            BQSD: '0',
        };
    },
    async mounted() {
        // 获取账户类型
        //this.accountType = await getAccountTypeName(this.cardList_3601, this.cardInfo_3004, this);
        this.MenuId = this.$route.params.id || '';
        await this.init();

        //this.getBaseData({ dictValue: '1082' }, 'CREDNOLIST');

        console.log('this.stmtplanList[0].code1', this.stmtplanList[0].code);
        //await this.getInitData(this.stmtplanList[0].code);
        //this.splitStringValue();


    },
    computed: mapState({
        defaultParams: state => state.common.defaultParams, // 接口默认参数
        cardAccountInfo_3001: state => state.common.cardAccountInfo_3001, // 账户信息
        cardList_3601: state => state.common.cardList_3601, // 卡列表信息
        cardInfo_3004: state => state.common.cardInfo_3004,
        defaultpinFlag: state => state.common.pinFlag,
        AccountionTYPE_INFO: state => state.common.AccountionTYPE_INFO, //账户类别列表
        isCurrentMenuInfo: state => state.menu.isCurrentMenuInfo,
        businessMenu: state => state.menu.businessMenu,
    }),
    methods: {
        async init() {
            console.log("到期还款日：" + this.cardAccountInfo_3001.DUEDATE + ",今日今时：" + moment().format('YYYY/MM/DD HH:mm:ss'));
            if (this.cardAccountInfo_3001.DUEDATE === moment().format('YYYYMMDD') && moment().format('HH') >= 17) {
                this.$alert(
                    "办理时间已超过还款截止日期下午五点，无法办理账单分期申请！",
                    '账单分期申请提示',
                    { customClass: 'warning', type: 'warning', showClose: false },
                ).then(() => {
                    closePage(this.$route, this, 1);
                });
            }
            console.log("默认账户类别：" + this.cardInfo_3004.CATEGORY);
            console.log("默认账户：" + this.cardInfo_3004.CARDNO);
            this.dailyForm.accttype = this.cardInfo_3004.CATEGORY + '';

            // 获取信用计划编号 下拉选择列表
            this.stmtplanList = await getDictSelectList('STMPLAN', this);
            //console.log('this.stmtplanList[0].code0', this.stmtplanList[0].code);
            //this.dailyForm.CREDNO = this.stmtplanList[0].code;
            //this.searchForm.cardno = this.cardInfo_3004.CARDNO;
            this.changeCardList(this.cardInfo_3004.CATEGORY + '');
            await this.getspeechList();
            await this.get3046();
        },
        changeCardList(val) {
            console.log("当前账户类型：" + val);
            let hasDefault = false; //是否包含默认卡
            this.cardList = [];
            this.cardList_3601.forEach((item) => {
                if (item.CATEGORY + '' === val) {
                    this.cardList.push(item);
                    if (item.CARDNBR === this.cardInfo_3004.CARDNO) {
                        hasDefault = true;
                    }
                }
            });

            //包含默认卡，卡号显示默认卡，不包含，显示cardList里第一张卡号
            if (hasDefault) {
                this.dailyForm.cardno = this.cardInfo_3004.CARDNO;
            } else {
                this.dailyForm.cardno = this.cardList[0].CARDNBR;
            }
        },
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            console.log("this.MenuId", this.MenuId);
            var checkParam = {
                'id': this.MenuId || this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        // 获取信用计划编号列表
        getBaseData(params, target) {
            this.$post.common.getBaseDataList(params).then((res) => {
                this[target] = res.data.content;
                this.dailyForm.CREDNO = (res.data.content !== null && res.data.content.length > 0) ? res.data.content[0].code : '';
            });
        },

        getFormData() {
            // 设置请求参数 -- 3001 交易
            const appBody = {
                CARDNO: this.cardInfo_3004.CARDNO, // 卡号
                PINFLAG: this.defaultpinFlag, // 是否检查密码标志 0-不检查
            };
            const params = JSON.parse(JSON.stringify(this.defaultParams));
            params.body.appHead.tranCode = '3001';
            params.body.appBody = appBody;

            // 跑 3001 交易
            this.$post.common.transPort(params).then((res) => {
                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    if (result.sysHead.rspCd === '000000') {
                        this.categoryMap = result.body.appBody;
                    } else {
                        this.$message.error(result.sysHead.rspMsg);
                    }
                } else {
                    this.$message.error('请求失败');
                }
            });
        },
        // 3046
        async get3046() {
            console.log('3046交易');
            this.defaultParams.sysHead.busiName = '欠款查询';
            // 3005 配置请求头
            const appBody_3046 = {
                OPT: 1, // 查询方式 1-用卡号查询 2-用证件号码查询
                CARDNBR: this.cardInfo_3004.CARDNO, // 卡号
                MPTYPE: 'Y', // 分期类型,y-账单分期
                STATUS: '30', // 分期申请状态,30-待请款
                PINFLAG: '0', // 是否检查密码标志 0-不检查
                RTNIND: '', // 翻页标志 首次传空， 翻页传1
                APPREF: '', // 分期申请编号，首次查询时送空， 下翻页查询时上送上次查询结果的最后一条记录返回的分期付款申请编号
            };
            const defaultParams_3046 = JSON.parse(JSON.stringify(this.defaultParams));
            defaultParams_3046.body.appHead.tranCode = '3046';
            defaultParams_3046.body.appBody = appBody_3046;
            await this.$post.common.transPort(defaultParams_3046).then((res) => {
                if (res.status === 200) {
                    const result = JSON.parse(res.data.jsonRes);
                    console.log("this.result3046:", result);
                    if (result.sysHead.rspCd === '000000') {
                        if (result.body.appBody.dataList.length > 0) {
                            this.stmtamt = result.body.appBody.dataList[0].MPAMT;



                        } else {
                            this.stmtamt = '0';
                        }
                    } else {
                        this.stmtamt = '0';
                    }
                    let close_cha = this.cardAccountInfo_3001.CLOSECHA; // 本币账单余额方向 3001-70
                    let close_bal = this.cardAccountInfo_3001.CLOSEBAL; // 本币账单余额 3001-69
                    const pymt_clud = this.cardAccountInfo_3001.PYMTCLUD; // 已结算付款额 3001-81
                    const cradj_s = this.cardAccountInfo_3001.CRADJS; // 本币贷记调整金额符号  3001-118
                    const cred_adj = this.cardAccountInfo_3001.CREDADJ; // 本币贷记调整金额 3001-117

                    const bq = parseFloat(close_cha + close_bal) - parseFloat(pymt_clud) + parseFloat(cradj_s + cred_adj) - parseFloat(this.stmtamt);
                    console.log("bq:" + bq);
                    this.UNBALFRE = parseFloat(bq).toFixed(2);
                    console.log("3046查询结果：", this.UNBALFRE);
                }
            });
        },
        // 可灵活分期付款的交易明细查询
        async searchData() {
            console.log("this.setMonthRate", this.setMonthRate);
            if (this.dailyForm.CREDNO === '') {

                this.$alert('分期计划编号为空，请先选择分期计划编号！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }
            // 需要一个接口获取分期期数数据
            // this.setMonthRate = await getInstalmentList(this.dailyForm.CREDNO, this);
            this.tryData = [
                {
                    OUTFLAG: this.setMonthRate[0].MPMONTH,
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                    discountRate: 0,
                },
            ];
            // 3053 配置请求头
            const appBody_3053 = {
                CARDNBR: this.cardInfo_3004.CARDNO,
                COVERTTY: 0, // 汇率种类
                PINFLAG: this.defaultpinFlag,
            };
            this.isLoading = true;
            this.showTrial = true;
            // 发送_3053 4052请求
            //3053查询账单应还款金额
            const result_3053 = await get_3xxx('3053', '账单分期查询', appBody_3053, this, false,);

            //4052查询上期账单信息
            const result_4052 = await this.get_4052('账单分期查询', 0, 0, 3, 0, 0, '156', this.dailyForm.CREDNO, 0);
            if (!result_4052 || !result_3053) return false;
            const res_3053 = result_3053.body.appBody;
            const res_4052 = result_4052.body.appBody;
            this.tran3053Form = res_3053;
            this.tran4052Form = res_4052;
            let appCredno = this.dailyForm.CREDNO;

            //如果本期已做过账单分期申请，展示已分期计划编号、分期金额、分期期数、月还款额、截止昨日未还账单余额
            if (this.tran4052Form.SMPFLAG === '1') {
                this.flag = true;
                this.haveAppData = [
                    {
                        CREDNO: appCredno,
                        NBRMTHS: this.tran4052Form.MONTHNBR,
                        AMT: this.tran4052Form.AMT.toFixed(2),
                        INSTALAMT: this.tran4052Form.INSTALAMT.toFixed(2),
                        UNSTM: this.tran4052Form.UNSTM.toFixed(2),
                    },
                ];
            } else {
                this.flag = false;
                this.haveAppData = [];
            }

            const openflagx = this.tran3053Form.OPENFLAGX; // 本期账单金额符号-美元  add by xj
            let openamtx = this.tran3053Form.OPENAMTX;		// 本期美元账单金额
            const minpayx = this.tran3053Form.MINPAYX;			// 最小还款额-美元
            const last_pay_amtx = this.tran3053Form.LASTPAYAMTX;		// 累计美元已还款金额
            if (openflagx === '-') {
                openamtx *= (-1);
            }
            const openflag = this.tran3053Form.OPENFLAG; // 本期账单金额符号-人民币  add by xj
            var openamt = this.tran3053Form.OPENAMT;		// 本期人民币账单金额
            let minpay = this.tran3053Form.MINPAY;			// 最小还款额
            let last_pay_amt = this.tran3053Form.LASTPAYAMT;		// 累计人民币已还款金额
            const un_balfre = this.tran4052Form.UNBALFRE;		// 截止昨日未还消费余额
            const { smp_flag } = this.tran4052Form;		// 当期是否已申请账单分期
            const smp_pamt = this.tran4052Form.SMPPAMT;		// 本期账单金额
            const rem_stmamt = this.tran4052Form.REMSTMAMT;	// 剩余可分期账单金额
            const { un_stm } = this.tran4052Form;	// 截止昨日未还账单余额
            var openamt = this.tran3053Form.OPENAMT; // 本期账单金额-人民币	add by xj
            const maxrefamt = '';//this.Form9064.cfgEdit; // "$!maxrefamt"最高可转分期金额选项，0-不限制，1-账单金额-最小还款额，2-账单金额比例，3-固定金额
            const maxrefamtper = '';//this.Form9105.cfgEdit; // "$!maxrefamtper"参考申请金额比例
            let refamt = '';
            if (openflag === '-') {
                openamt *= (-1);
            }
            if (this.tran4052Form.CURRNUM === '840') {
                openamt = openamtx;
                minpay = minpayx;
                last_pay_amt = last_pay_amtx;
            }
            //this.UNBALFRE = parseFloat(un_balfre).toFixed(2);
            openamt = parseFloat(openamt).toFixed(2);
            if (maxrefamt === '1') {
                // PRCPD中，最高可转分期金额选项为“账单金额-最小还款额”，余额类型为“消费”，如果分次申请，可能比单次申请的金额要大，可采用PRCPD的参数“账单分期间隔期数”控制
                // 计算规则：min[(账单金额-最小还款额),截止昨日未还消费余额]
                refamt = parseFloat(openamt) - parseFloat(minpay);
                if (parseFloat(un_balfre) < refamt) {
                    refamt = parseFloat(un_balfre);
                }
            } else if (maxrefamt === '2') { // 参考申请金额比例>0：参考申请金额＝剩余可申请账单分期余额×参考申请金额比例/100； add by hrh 20151021
                refamt = rem_stmamt * maxrefamtper / 100.0;
            } else {
                // 徽商银行PRCPD，最高可转分期金额选项为“不限制”，余额类型为“消费”
                // 计算规则：账单余额，可以直接取参考申请金额字段
                refamt = parseFloat(smp_pamt);
            }
            if (refamt < 0) {
                refamt = 0;
            }
            this.openamt = openamt;
            this.refamt = refamt.toFixed(2);
            this.payAcount = '';
            this.difference = '';

            let crdno = '';
            for (let i = 0; i < this.stmtplanList.length; i++) {
                if (appCredno === this.stmtplanList[i].code) {

                    crdno = appCredno + '-' + this.stmtplanList[i].label;
                    console.log(crdno);
                }
            }
            console.log("4052查询结果：", this.UNBALFRE);
            this.stmtData = [
                {

                    CREDNO: crdno,
                    OPENAMT: openamt,
                    REFAMT: this.tran4052Form.SMPPAMT.toFixed(2),
                    UNBALFRE: this.UNBALFRE,
                    REMSTMAMT: this.tran4052Form.REMSTMAMT.toFixed(2),
                    payAcount_val: '',
                    BALANCEMAMT: '',
                }];

        },
        // 请求 4052
        async get_4052(masg, COVERTTY, PINFLAG, OPERTP, PRMCHK, CLSCHK, CURRNUM, CREDNO, NBRMTHS = '', AMT = '', discountRate) {
            // 4052 配置请求头
            const appBody_4052 = {
                CARDNBR: this.cardInfo_3004.CARDNO,
                COVERTTY, // 汇率种类
                PINFLAG,
                OPERTP, // 操作类型 0－申请 1－撤销 2—查询 3—上期账单信息查询 4-预申请
                PRMCHK,
                CLSCHK,
                CURRNUM,
                CREDNO,
                NBRMTHS, // 分期期数
                AMT: AMT, // 分期金额
                FEEPCNTPN: discountRate,
            };

            const result_4052 = await get_4xxx('4052', masg, appBody_4052, this);
            if (!result_4052) return false;
            return result_4052;
        },
        // 切换信用计划编号
        changeData() {
            this.tryData = [
                {
                    OUTFLAG: '',
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                },
            ];
        },
        // 切换分期期数
        toCount11() {
            //this.handleGetComputeAmt();
            this.handleGetComputeMP(this.payAcount);
        },
        // 获取计算后的金额
        async handleGetComputeAmt() {
            // 4089 配置请求头
            const appBody_4089 = {
                CARDNBR: this.cardInfo_3004.CARDNO,
                OPT: 1,
                PINFLAG: this.defaultpinFlag,
                CREDNO: this.dailyForm.CREDNO,
                NBRMTHS: this.tryData[0].OUTFLAG || '', // 分期期数
                BILLAMT: this.payAcount,
                CURRNUM: '156',
            };
            const result_4089 = await get_3xxx(
                '4089',
                '账单分期试算',
                appBody_4089,
                this,
            );
            if (!result_4089) return false;
            // 成功之后当前显示
            const feeInstl = result_4089.body.appBody.FEEINSTL; // 月手续费
            const instalAmt = result_4089.body.appBody.INSTALAMT; // 每期分摊本金
            const feeAmt = result_4089.body.appBody.FEEAMT; // 总手续费
            const feePcnt = result_4089.body.appBody.FEEPCNT; // 利率
            const feeFlag = result_4089.body.appBody.FEEFLAG; // 0：一次性收取 1：分期收取
            const mp_irr = result_4089.body.appBody.MPIRR; // 年化利率
            const { NBRMTHS } = result_4089.body.appBody; // 分期期数

            const amount = this.payAcount;
            const mon = parseInt(NBRMTHS);
            // 首期还款额 = 本金 / 期数 + 总手续费
            const firstAmts = amount / mon + feeAmt;

            // 总还款额 = 总手续费 + 本金
            const allcountfee = feeAmt + amount * 1;
            console.log(feeAmt, amount);

            // 本金 = 本金 / 期数
            let corpus = 0;
            corpus = amount / mon;
            // if (feeFlag == 0) {
            //   feeAmt = feeAmt * 0.75;
            //   firstAmts = (firstAmts - corpus) * 0.75 + corpus;
            //   allcountfee = allcountfee - feeAmt / 3;
            // }
            // 月还款额 = 本金 + 月手续费
            this.tryData[0].REMONTHFEE = ((corpus + feeInstl) * 1).toFixed(2);
            this.tryData[0].FEEINSTL = feeInstl.toFixed(2);
            this.tryData[0].INSTALAMT = instalAmt.toFixed(2);
            this.tryData[0].ALLCOUNTFEE = (allcountfee * 1).toFixed(2);
            // 首期还款额 = 本金 / 期数 + 总手续费
            this.tryData[0].CORPUS = (firstAmts * 1).toFixed(2);
            this.tryData[0].ALLMONTHSFEE = feeAmt.toFixed(2);
            this.tryData[0].MPIRR = mp_irr;
        },
        // ForDight(Dight,How):数值格式化函数;
        // Dight:要格式化的 数字;
        // How::要保留的小数位数。
        ForDight(Dight, How) {
            var Dight = Math.round(Dight * Math.pow(10, How)) / Math.pow(10, How);
            return Dight;
        },
        handleBlur() {
            console.log(this.stmtData[0].payAcount_val);
            //let cardnoreg = /^\d|\d\.\d{1,2}+$/;
            let cardnoreg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;

            this.payAcount = this.stmtData[0].payAcount_val;
            if (this.payAcount === '') {
                return;
            }

            if (!cardnoreg.test(this.payAcount)) {
                this.$alert('输入申请金额非法，请输入正确的金额数字！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                this.stmtData[0].payAcount_val = '';
                return;
            }
            if (parseFloat(this.payAcount) < 500 || parseFloat(this.payAcount) > this.stmtData[0].REFAMT) {
                this.$alert('请输入介于500和参考申请金额之间的数值！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }
            // 取
            const balance = this.UNBALFRE - this.payAcount;
            //this.difference = `本期账单金额 - 当前分期金额  = ${this.ForDight(balance, 2)}`;
            this.stmtData[0].BALANCEMAMT = this.ForDight(balance, 2);
            //this.handleGetComputeAmt();
            this.handleGetComputeMP(this.payAcount);
        },

        // 1、手续费支付方式。0：首期支付；1：分摊支付
        // 2、总手续费 = 费率*本金
        // 3、总还款额  = 总手续费+本金
        // 4、每期手续费（分摊支付方式） = 总手续费/分期期数
        // 5、月还款额（分摊支付方式）= 本金/分期期数+总手续费/分期期数

        // 6、如果是首期支付，首期还款额 = 本金/分期期数 + 总手续费
        // 	月还款额 = 本金/分期期数 
        // 
        handleGetComputeMP(mpamt) {

            let nmth = this.tryData[0].OUTFLAG;    //分期期数

            console.log(this.setMonthRate + ',mpamt:', mpamt + ',nmth:' + this.tryData[0].OUTFLAG + ',rt:' + this.tryData[0].FEEINSTL + ',credno:' + this.dailyForm.CREDNO);
            const MPAMT_value = mpamt * 1;

            let mpfee = '';//费率
            let feetype = '';//手续费收取方式
            let discountRate = '';
            for (let i = 0; i < this.setMonthRate.length; i++) {
                if (this.setMonthRate[i].MPMONTH === this.tryData[0].OUTFLAG) {
                    mpfee = this.setMonthRate[i].MPFEE;
                    feetype = this.setMonthRate[i].PMmethod;
                    this.feetype = this.setMonthRate[i].PMmethod;
                    discountRate = this.setMonthRate[i].discountRate;
                }
            }
            //总手续费 = 分期金额*费率
            let totalfee = parseFloat(mpamt * mpfee).toFixed(2);
            console.log(totalfee);

            //总还款额 = 分期本金+总手续费
            let totamt = parseFloat(mpamt) + parseFloat(totalfee);

            let monthPay = '';//月还款额
            let firstPay = '';//首期还款额


            if (feetype === '0') {
                //首期支付：月还款额 = 分期本金/分期期数
                //首期支付：首期还款额 = 月还款额+总手续费
                monthPay = parseFloat(mpamt / nmth).toFixed(2);
                firstPay = parseFloat(monthPay) + parseFloat(totalfee);
            } else {
                //分摊支付：月还款额 = 总还款额/分期期数
                //分摊支付：首期还款额 = 月还款额
                monthPay = parseFloat(totamt / nmth).toFixed(2);
                firstPay = monthPay;
            }

            // 月还款额 = 本金 + 月手续费
            this.tryData[0].REMONTHFEE = parseFloat(monthPay).toFixed(2);
            this.tryData[0].ALLCOUNTFEE = parseFloat(totamt).toFixed(2);
            this.tryData[0].CORPUS = parseFloat(firstPay).toFixed(2);
            this.tryData[0].ALLMONTHSFEE = parseFloat(totalfee).toFixed(2);
            this.tryData[0].discountRate = discountRate;

            this.secondConfirm = {
                totalAmount: mpamt,
                pmethod: feetype === '0' ? '一次性收取' : '按月摊还',
                months: nmth,
                rate: (mpfee * 100).toFixed(2) + '%',
            };
        },

        // 申请
        async handleApplication() {
            console.log("this.selectedList.length", this.selectedList.length);
            if (this.selectedList.length != this.speechList.length) {
                this.$alert('话术尚未全部勾选！', '提示', {
                    customClass: 'warning', type: 'warning',
                });
                return;
            }
            const amt = this.payAcount;
            if (parseFloat(amt) < 200 || parseFloat(amt) > this.refamt) {
                this.$alert('请输入介于500和参考申请金额之间的数值！');
                return;
            }
            // 再次确定是否申请
            this.secConfirmDialogVisible = true;
        },
        async handletrans() {
            this.secConfirmDialogVisible = false;

            const result_4052 = await this.get_4052(
                '账单分期申请',
                0,
                0,
                0,
                0,
                0,
                '156',
                this.dailyForm.CREDNO,
                this.tryData[0].OUTFLAG,
                this.payAcount,
                this.tryData[0].discountRate,
            );
            if (!result_4052) return false;
            const res = result_4052.body.appBody;

            // 配置成功之后展示的数据
            this.statementsuccess = [
                { keys: '主卡卡号 : ', values: res.CARDNBR },
                { keys: '分期金额 : ', values: res.AMT },
                { keys: '每月还款额 : ', values: this.feetype === '0' ? res.INSTALAMT : parseFloat(parseFloat(res.INSTALAMT) + parseFloat(res.FEEAMT / res.MONTHNBR)).toFixed(2) },
                { keys: '分期期数 : ', values: res.MONTHNBR },
                { keys: '总手续费 : ', values: res.FEEAMT },
                { keys: '办理时间 : ', values: moment().format('YYYY/MM/DD HH:mm:ss') },
                { keys: '手续费分摊方式 : ', values: this.feetype === '0' ? '一次性收取' : '按月分摊' }
            ];
            this.showsuccess = true;
            this.searchData();
        },
        // 多期数试算结果
        handleClicksuInfo() {

            //1拆分字典值
            const trial = [];
            console.log("this.setMonthRate33333", this.setMonthRate);
            this.setMonthRate.forEach((item) => {
                this.getTralDataList(item, trial);
            })
            console.log('trial', trial);
            this.TrialDataList = trial;
            console.log('TrialDataList期数列表', this.TrialDataList);
            if (this.setMonthRate[0].PMmethod === '1') {
                this.DialogVisible = true;
            } else {
                this.DialogVisible1 = true;
            }

        },

        // 拼装多种期数的费率数据结构
        getTralDataList(item, trial) {
            console.log("this.payAcount", this.payAcount);
            console.log('item', item);
            const MPFEENum = item.MPFEE;//费率
            const MPAMT_value = (this.payAcount || 0) * 1; //分期金额
            const totalHandling = (MPFEENum * MPAMT_value).toFixed(2);//总手续费 费用总额
            const totalRepayment = (totalHandling * 1 + MPAMT_value).toFixed(2);//总还款额
            let monthlyPayment = 0;////每期分摊金额
            let FirstIssue = 0;//首期还款额 第一期分摊金额
            let monthlyPrincipal = 0;//每期分摊本金
            let monthlyCost = 0;//每期分摊费用

            // 每期分摊本金
            monthlyPrincipal = (MPAMT_value / item.MPMONTH).toFixed(2);
            if (item.PMmethod === "1") {
                // 每期手续费（分摊支付方式）

                //每期分摊费用   =  费用总额/ item.nbrMths
                monthlyCost = (totalHandling / item.MPMONTH).toFixed(2);

                // 月还款额 每期分摊金额
                monthlyPayment = ((MPAMT_value / item.MPMONTH).toFixed(2) * 1 + (totalHandling / item.MPMONTH).toFixed(2) * 1).toFixed(2);
            } else {
                // 首期还款额  第一期分摊金额 = 每期分摊本金+费用总额
                FirstIssue = (MPAMT_value / item.MPMONTH).toFixed(2) * 1 + parseFloat(totalHandling);
            }
            const itemList = {
                MPMONTH: item.MPMONTH,//
                Bystages: MPAMT_value,//分期金额
                totalHandling: totalHandling,////总手续费 费用总额
                totalRepayment: totalRepayment,//总还款额
                rate: parseFloat(MPFEENum * 100.0).toFixed(2) + '%',//费率
                monthlyPrincipal: monthlyPrincipal,//每期分摊本金
                monthlyCost: monthlyCost,//每期分摊费用
                FirstIssue: parseFloat(FirstIssue).toFixed(2),//第一期分摊金额
                monthlyPayment: monthlyPayment,// 每期分摊金额
                interest: item.interest,//利率
            }
            console.log("itemList1111:", itemList);
            trial.push(itemList)
        },
        async getCREDNOValue(val) {
            // this.splitDictValue(val);
            await this.getInitData(val);
            this.splitStringValue();

            this.searchData();

        },

        // 查分分期期数和费率，手续费分摊方式 3-0.024-1,6-0.0468-1  
        // MPMONTH_list: '',//分期期数列表
        // MPFEE_list: '',//费率
        // 手续费支付方式
        splitStringValue() {
            const nbrMthsArray = this.IccMpprm.nbrMths.split(','); //期数
            const appFeeratioArray = this.IccMpprm.appFeeratio.split(',');//费率
            const interestRateArray = this.IccMpprm.interestRate.split(',');//利率
            const paytypeArray = this.IccMpprm.paytype.split(',');//手续费分摊方式
            const discountRate = this.IccMpprm.discountRate;//手续费折扣率
            const MPoption = [];
            nbrMthsArray.forEach((item, index) => {
                // const itemArray = item.split('-');
                console.log('nbrMthsArray', item, index);
                MPoption[index] = {
                    MPMONTH: item,//分期期数
                    MPFEE: appFeeratioArray[index],////费率
                    PMmethod: paytypeArray[index],//，手续费分摊方式
                    interest: interestRateArray[index],//利率
                    label: item + '期--费率:' + (appFeeratioArray[index] * 100).toFixed(2) + '%',
                    discountRate: discountRate,//账单分期折扣率
                }
            })
            this.setMonthRate = JSON.parse(JSON.stringify(MPoption));
            console.log('setMonthRate', this.setMonthRate);
            this.tryData[0].OUTFLAG = this.setMonthRate[0].MPMONTH;
            this.toCount11();
        },

        // 获取分期计划对应的数据
        async getInitData(val) {
            let params = {
                pageNum: 1,
                pageSize: 10,
                itemNo: val,
            };
            await this.$post.MpprmPlan.pageIccMpprm(params).then((res) => {
                if (res.data.success) {
                    this.IccMpprm = res.data.content.records[0];
                    console.log('分期计划__IccMpprm', this.IccMpprm);
                } else {
                    this.$alert('分期计划数据请求失败', '提示', {
                        customClass: 'warning', type: 'warning',
                    });
                }

            });
        },
        applicationRecords() {
            this.MenuId = getBusinessMenuId('/carPeriodic/mptransrecordqry', this.businessMenu);
            console.log('this.MenuId____', this.MenuId);
            this.$router.push({ name: 'mptransrecordqry', path: '/carPeriodic/mptransrecordqry', params: { id: this.MenuId } });

        },
        // 将组件返回的false赋值给当前
        close(data) {
            this.showsuccess = data;
        },
    },
};
</script>

<style  scoped lang="scss">
#insBillAppli-contnair .el-form-item {
    text-align: center;
}
.footer {
    text-align: center;
    margin-top: 10px;
    margin-bottom: 18px;
}
.query {
    text-align: right;
    margin-top: 10px;
    margin-bottom: 18px;
}
</style>
